<?php


namespace app\common\controller;

use think\Controller;
use think\facade\App;
use think\Image;
use think\facade\Session;

class Common extends Controller
{
    public function initialize()
    {
        parent::initialize();
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With,content-type');
        header("Access-Control-Allow-Methods: OPTIONS,POST,GET,DELETE,PUT");
        //判断用户是否存在

    }

    /**
     * 正确信息
     * @param string $msg
     * @param array $data
     * @param string $url
     * @return \think\response\Json
     */
    public function okJson($msg = '', $data = [], $url = '')
    {
        $json = ['code' => 0];
        if (!empty($msg)) $json['msg'] = $msg;
        if (!empty($url)) $json['url'] = $url;
        if (!empty($data)) $json['data'] = $data;
        return json($json);
    }

    /**
     * 错误信息
     * @param string $msg
     * @param string $url
     * @return \think\response\Json
     */
    public function errJson($msg = '', $data = '')
    {
        $json = [
            'code' => -1,
            'msg' => $msg,
            'data' => $data
        ];
        return json($json);
    }

    /**
     * 分页数据
     * @param array $data
     * @param int $total
     * @return \think\response\Json
     */
    public function
    listJson($data = [], $total = 0)
    {
        $json = [
            'code' => 0,
            'data' => $data,
            'count' => $total
        ];
        return json($json);
    }

    /**
     * 获取分页数量
     * @return int
     */
    public function getPageSize()
    {
        return $this->request->param('limit', 10);
    }

    /**
     * 获取请求页
     * @return int
     */
    public function getPage()
    {
        return $this->request->param('page', 1);
    }


    /**
     * 生成api token
     * @return string
     */
    public function setToken()
    {
        return md5(uniqid() . time());
    }

    //无限级分类
    function make_tree($arr, $pid = 0, $column_name = 'id|pid|children')
    {
        list($idname, $pidname, $cldname) = explode('|', $column_name);
        $ret = array();
        foreach ($arr as $k => $v) {
            if ($v [$pidname] == $pid) {
                $tmp = $arr [$k];
                unset($arr [$k]);
                $tmp [$cldname] = self::make_tree($arr, $v [$idname], $column_name);
                $ret [] = $tmp;
            }
        }
        return $ret;
    }

    //上传文件
    /**
     * @param $filename 表单name值
     * @param bool $isthumb 是否需要压缩缩略图
     * @return array
     */
    public function upfile($filename,$thumb=[])
    {
        header("Content-Type: text/html;charset=utf-8");
        $file = request()->file($filename);
        // 移动到框架应用根目录/uploads/ 目录下
        $dir=App::getRootPath();
        $info = $file->move($dir.'public/uploads/');
        if ($info) {
            $filepath = str_replace('\\','/',$info->getSaveName());
            $result=[
                'code'=>2,
                'filepath'=>'/uploads/'.$filepath,
                'thumb'=>'/static/images/thumb.jpg'
            ];
            // 成功上传后 获取上传信息
            if(count($thumb)>0) {
                $saveName = $info->getSaveName();
                $image = Image::open($dir.'public/uploads/'.$saveName);
                $tpath =$dir.'public/uploads/'.str_replace('.'.$info->getExtension(),'',$filepath).'_thumb.'.$info->getExtension();
                $thumbpaht = '/uploads/'.str_replace('.'.$info->getExtension(),'',$filepath).'_thumb.'.$info->getExtension();
                // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
                $image->thumb($thumb[0],$thumb[1])->save($tpath);
                $result['thumb']=$thumbpaht;
            }
        } else {
            // 上传失败获取错误信息
            return $file->getError();
        }
        return $result;
    }

    //生成唯一订单号
    function build_order_no()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    //数组排序
    public function my_sort($array, $sortkey, $sortorder)
    {

        $newArr = array();

        foreach ($array as $key => $v) {
            $newArr[$key][$sortkey] = $v[$sortkey];
        }
        array_multisort($newArr, $sortorder, $array);//SORT_DESC为降序，SORT_ASC为升序
        return $array;

    }

    //获取终端ip
    function get_client_ip()
    {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
    }

    /*
    * 1.纬度1，经度1，纬度2，经度2
    * 2.返回结果是单位是KM。
    * 3.保留一位小数
    */
    function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371;
        return round($s, 1);
    }

    //密码加密
    function samd5($sa, $str)
    {
        $str1 = substr(md5($str), 0, 8);
        $str2 = substr(md5($str), 8, 31);
        return $str1 . $sa . $str2;
    }

    /**
     * @desc arraySort php二维数组排序 按照指定的key 对数组进行排序
     * @param array $arr 将要排序的数组
     * @param string $keys 指定排序的key
     * @param string $type 排序类型 asc | desc
     * @return array
     */
    function arraySort($arr, $keys, $type) {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v){
            $keysvalue[$k] = $v[$keys];
        }
        $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }

}